<template>
  <div class="merchantManagement">
    <div class="operate-container">
      <div class="leftArea">
        <el-input
          style="width: 210px"
          clearable
          v-model="searchParams.name"
          placeholder="请输入店铺名称"
        />
        <span>是否入驻</span>
        <el-select
          style="width: 160px"
          clearable
          v-model="searchParams.settled">
          <el-option
            v-for="item in settledOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span>店铺状态</span>
        <el-select
          style="width: 160px"
          clearable
          v-model="searchParams.status">
          <el-option label="正常" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
        <span>所属分类</span>
        <el-cascader
          style="width: 340px;"
          v-model="searchParams.categoryList"
          :options="categoryList"
          collapse-tags
          clearable
          :props="{
            value: 'id',
            label: 'name',
            expandTrigger: 'hover',
            multiple: true
          }"
        />
        <el-button
          class="marginLeft14"
          type="primary"
          @click="handleSearch">
          查询
        </el-button>
      </div>
      <div class="rightArea">
        <el-button
          type="primary"
          @click="handleCreateShop">
          新增商家
        </el-button>
      </div>
    </div>
    <div class="inner-container">
      <el-table
        stripe
        v-loading="loading"
        :data="tableData"
        :height="'calc(100vh - 245px)'">
        <el-table-column
          fixed
          align="left"
          label="序号"
          width="60">
          <template #default="scope">
            {{ (searchParams.pageNum - 1) * searchParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="店铺名称" prop="name" width="200"></el-table-column>
        <el-table-column align="left" label="所属分类" width="300">
          <template #default="scope">
            {{scope.row.firstLevel}}/{{scope.row.secondLevel}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="联系电话" prop="phone" width="120"></el-table-column>
        <el-table-column align="left" label="地址" prop="address" width="160"></el-table-column>
        <el-table-column align="left" label="联系人" prop="contacts" width="80"></el-table-column>
        <el-table-column
          align="left"
          label="数据">
          <template #default="scope">
            <el-space>
              <el-tag type="info">评分{{ scope.row.score }}</el-tag>
              <el-tag type="info">评论{{ scope.row.scoreNum }}</el-tag>
              <el-tag type="success">点赞{{ scope.row.good }}</el-tag>
              <el-tag type="danger">反对{{ scope.row.bad }}</el-tag>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column align="left" label="更新日期" prop="updateTime" width="160"></el-table-column>
        <el-table-column align="left" label="商家账号" prop="userName" width="160"></el-table-column>
        <el-table-column
          fixed="right"
          align="left"
          label="操作"
          width="300">
          <template #default="scope">
            <el-button size="small" @click="handleResetPassword(scope.row)">
              重置密码
            </el-button>
            <el-button size="small" @click="handleEditShopCourse(scope.row)">
              菜单管理
            </el-button>
            <el-button size="small" @click="handleEditShop(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteShop(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[20, 50, 100]"
          :total="searchParams.total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
        />
      </div>
    </div>
  </div>
</template>
<script setup>
import { listMerchant, delMerchant, addMerchantUser } from "@/api/merchant/index.js";
import { listCategory } from "@/api/category/index.js";
import {handleConfirmDelete} from "@/utils/myUtils.js";
import { ElMessage, ElMessageBox } from 'element-plus'

//获取商家分类
onMounted(() => { getCategoryList() });
const categoryList = ref([])
const getCategoryList = () => {
  listCategory().then(res => {
    const { data } = res;
    categoryList.value = data;
  })
}

const settledOption = reactive([
  { label: '未入驻', value: 0 },
  { label: '入驻', value: 1}
])

const searchParams = reactive({
  name: "",
  settled: undefined,
  status: undefined,
  categoryList: [],
  pageNum: 1,
  pageSize: 20,
  total: 0,
})

//列表数据获取
onMounted(() => { getTableData() })
const tableData = ref([]);
const loading = ref(false)
const getTableData = () => {
  loading.value = true
  //所属分类参数
  const { categoryList } = searchParams;
  let firstLevel = "", secondLevel = "";
  if (categoryList && categoryList.length > 0) {
    firstLevel = categoryList[0][0];
    categoryList.forEach(item => {
      secondLevel += item[1] + ','
    })
    secondLevel = secondLevel.split(',').slice(0, -1).join(',')
  }
  const params = {
    ...searchParams,
    firstLevel,
    secondLevel,
  };
  delete params.categoryList;
  delete params.total;
  listMerchant(params).then(response => {
    tableData.value = response.rows;
    searchParams.total = response.total;
    loading.value = false;
  })
}

const handleSearch = () => {
  searchParams.pageNum = 1;
  getTableData();
}

const handleCurrentChange = (v) => {
  searchParams.pageNum = v;
  getTableData();
}

const handleSizeChange = (v) => {
  searchParams.pageNum = 1;
  searchParams.pageSize = v;
  getTableData();
}

//新增商家
const router = useRouter()
const handleCreateShop = () => {
  router.push({
    path: '/merchantAdd',
    query: {
      id: undefined
    }
  })
}

//重置密码
const handleResetPassword = (data) => {
  const { id } = data;
  ElMessageBox.prompt('密码格式：至少8位数，只能含有英文+数字', '设置商家登陆密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/,
    inputErrorMessage: '请输入正确格式的密码！'
  })
    .then(({ value }) => {
      const params = { id, password: value };
      addMerchantUser(params).then(res => {
        getTableData();
        ElMessage({
          message: '重置成功',
          type: 'success',
        })
      })
    })
    .catch(() => {

    })
}

//编辑商家
const handleEditShop = (data) => {
  const { id } = data
  router.push({
    path: '/merchantAdd',
    query: { id }
  })
}

//删除商家
const handleDeleteShop = async (data) => {
  await handleConfirmDelete();
  const { id } = data
  delMerchant(id).then(response => {
    getTableData();
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
  })
}

//菜单管理
const handleEditShopCourse = (data) => {
  const { id, name } = data
  router.push({
    path: '/courseManagement',
    query: { id, name }
  })
}

</script>
<style lang="scss" scoped>
.merchantManagement {
  width: 100%;
  padding: 15px;
  >div.operate-container {
    width: 100%;
    height: 60px;
    padding: 0 15px;
    box-sizing: border-box;
    margin-bottom: 15px;
    background-color: #f5f6f8;
    display: flex;
    align-items: center;
    justify-content: space-between;
    >div.leftArea {
      span {
        color: #343d59;
        font-size: 14px;
        &:not(:first-child) {
          margin: 0 14px;
        }
      }
      .el-select {
        width: 200px;
        :deep( .el-input__inner ){
          height: 30px !important;
        }
      }
    }
    >div.rightArea {

    }
  }
  >div.inner-container {
    div.pagination {
      height: 40px;
      line-height: 40px;
      background-color: #ffffff;
      margin-top: 10px;
      .el-pagination {
        float: right;
        margin-right: 30px;
      }
    }
  }
}
</style>
